
import * as path from 'path';
import * as fs from 'fs';
import { Readable } from 'stream';

// 常量配置
const CONSTANTS = {
	ROOT: path.join(process.cwd(), 'assets'),
	STATIC_ASSETS: ['/', 'html', 'css', 'js'],
	CONTENT_TYPES: {
		html: 'text/html;charset=utf-8',
		css: 'text/css;charset=utf-8',
		js: 'application/javascript;charset=utf-8',
	}
};

/**
 * 处理静态资源请求
 * @param {string} filePath - 文件路径
 * @param {http.ServerResponse} res - 响应对象
 */
function serveStaticFile(req, res) {
	const filePath = path.join(
		CONSTANTS.ROOT,
		req.url === '/' ? 'index.html' : req.url
	);
	const ext = path.extname(filePath).slice(1);
	const contentType = CONSTANTS.CONTENT_TYPES[ext];

	try {
		const stream = fs.createReadStream(filePath);
		res.writeHead(200, { 'Content-Type': contentType });
		stream.pipe(res);
	} catch (error) {
		notfound(res)
	}
}

/**
 * 流式传输模拟大文件下载
 * @param {http.ServerResponse} res - 响应对象
 */
function handleLargeFile(res) {
	res.writeHead(200, {
		'Content-Type': 'application/octet-stream',
		'Content-Disposition': 'attachment; filename="download.txt"'
	});

	const readableStream = new Readable({
		read() {
			// 启动后会按秒间隔写入数据
			// 每秒写入 1MB 数据，直到达到 10MB
			setTimeout(() => {
				if (this.totalSize < 26) {
					const chunk = generateRandomLetters(1); // 每次生成 1byte 数据
					this.push(chunk); // 推送数据块
					this.totalSize += chunk.length;
					console.log(`已发送 ${this.totalSize} 字节`);
				} else {
					this.push(null);  // 结束流
				}
			}, 1000);  // 1000毫秒 = 1秒
		}
	});

	// 初始化 totalSize
	readableStream.totalSize = 0;

	// 生成随机字母块的函数
	function generateRandomLetters(bytes) {

		// 定义随机字母字符集（仅包含大小写字母）
		const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		return charset[readableStream.totalSize];
	}

	// 将流管道传输到响应对象
	readableStream.pipe(res);
}


export function GET(req, res) {
	// 处理静态资源
	const reqType = req.url.split('.').at(-1);
	if (CONSTANTS.STATIC_ASSETS.includes(reqType)) {
		return serveStaticFile(req, res);
	}

	// 处理API请求
	switch (req.url) {
		case '/largeFile':
			handleLargeFile(res);
			return;
		default:
			notfound(res);
	}

	// 请求关闭时清理资源
	req.on('close', () => {

	});
}

/**
 * 发送404响应
 * @param res {http.ServerResponse} 响应对象
*/
function notfound(res) {
	res.writeHead(404, { 'Content-Type': 'text/plain;charset=utf-8' });
	res.end('页面找不到');
}